package weibo.crawler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import data.process.UO.friendshipUO;
import data.process.UO.friendshipUODAO;

import weibo.crawler.UO.RawUserUO;
import weibo.crawler.UO.RawUserUODAO;
import weibo4j.Friendships;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.model.PostParameter;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;
import weibo4j.util.WeiboConfig;

public class crawler {
	public static void main(String [] args) throws WeiboException, IOException{
		Oauth oauth = new Oauth();
		BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
		System.out.print("Hit enter when it's done.[Enter]:");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String code = br.readLine();
		Log.logInfo("code: " + code);

		Weibo weibo = new Weibo();
		weibo.setToken(oauth.getAccessTokenByCode(code).getAccessToken());
				
		String uid = "1397095161";
		Users um = new Users();
		User user = um.showUserById(uid);

		Log.logInfo(user.toString());

		Friendships fm = new Friendships();
		List<String> uidList = new ArrayList<String>();
		List<User> users = fm.getFollowersById(uid);
		for (User u : users)
			uidList.add(u.getId());
		for(String userid : uidList) {
			try {
				List<User> users_tmp = fm.getFollowersById(userid);
				for(User u : users_tmp){
					Log.logInfo(u.toString());
					RawUserUODAO dao = new RawUserUODAO();
					RawUserUO recordUser = new RawUserUO();
					recordUser.setUser(u);
					dao.save(recordUser);
					friendshipUO friendship = new friendshipUO();
					friendship.setUid(userid);
					friendship.setFollowid(u.getId());
					friendshipUODAO dao2 = new friendshipUODAO();
					dao2.save(friendship);
				}
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}
//		RawUserUO recordUser = new RawUserUO();
//		recordUser.setUser(user);
		
//		Configuration cfg = new Configuration();
//		SessionFactory sf = cfg.configure().buildSessionFactory();
//		Session session = sf.openSession();
//		session.beginTransaction();
//		session.save(recordUser);
//		session.getTransaction().commit();
//		session.close();
//		sf.close();

		
//		Weibo.client.post(WeiboConfig.getValue("baseURL")+"statuses/update.json",new PostParameter[]{
//			new PostParameter("source", WeiboConfig.getValue("client_ID")),
//			new PostParameter("status", "test"),
//		});

	}

}
